package com.wxy.ej.nosql.modules.collectiondata.controller;

import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.base.Result;
import com.wxy.ej.nosql.modules.collectiondata.repository.CollectionDataRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RequestMapping("/innerService/collectionData")
@RestController
public class CollectionDataController {

    @Autowired
    private CollectionDataRepository collectionDataRepository;

    @PostMapping("/saveJson")
    public Result saveJson(@RequestBody JSONObject jsonObject, @RequestParam String collectionName)  {
        System.out.println("jsonObject");
        System.out.println(jsonObject);
        collectionDataRepository.saveJson(jsonObject, collectionName);
        return Result.builder();
    }

    /**
     * 根据key查询，存在则覆盖
     * @param jsonObject
     * @param collectionName
     * @param key
     * @return
     */
    @PostMapping("/saveJsonUnique")
    public Result saveJsonUnique(@RequestBody JSONObject jsonObject, @RequestParam String collectionName, @RequestParam String key)  {
        System.out.println("jsonObject");
        System.out.println(jsonObject);
        System.out.println("key");
        System.out.println(key);
        if (key==null || key.trim().length()==0) {
            collectionDataRepository.saveJson(jsonObject, collectionName);
            return Result.builder();
        }
        JSONObject dbDataJsonObject = collectionDataRepository.queryByKey(collectionName, key, jsonObject.get(key));
        if (dbDataJsonObject==null) {
            collectionDataRepository.saveJson(jsonObject, collectionName);
        }else{
            jsonObject.put("_id", dbDataJsonObject.get("_id"));
            collectionDataRepository.saveJson(jsonObject, collectionName);
        }
        return Result.builder();
    }


    @PostMapping("/query")
    public Result query(@RequestBody JSONObject queryJsonObject, @RequestParam String collectionName)  {
        System.out.println("queryJsonObject");
        System.out.println(queryJsonObject);
        List list =  collectionDataRepository.query(collectionName);
        return Result.builder().setList(list);
    }


    @PostMapping("/page")
    public Result page(@RequestBody JSONObject queryJsonObject, @RequestParam String collectionName)  {
        System.out.println("queryJsonObject");
        System.out.println(queryJsonObject);

        String mql = queryJsonObject.getString("mql");
        if (StringUtils.isBlank(mql)) {
            return  collectionDataRepository.page(queryJsonObject, collectionName);
        }else{
            return  collectionDataRepository.pageMql(queryJsonObject, collectionName);
        }
    }


}
